package com.example.woke;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.config.BoxingCropOption;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.BoxingFileHelper;
import com.bilibili.boxing.utils.ImageCompressor;
import com.bilibili.boxing_impl.ui.BoxingActivity;
import com.bumptech.glide.Glide;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.netease.nim.uikit.GlideApp;
import com.woke.method.CommonUtils;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import net.bither.util.NativeUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.EasyPermissions;

public class RealnameActivity extends AppCompatActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {
	private static final int MAX_IMAGE_SIZE = 100 * 1024;
	private static final int REQUEST_CODE_FRONT = 8;  //正面照
	private static final int REQUEST_CODE_REVERSE = 2; //反面照
	private static final int REQUEST_CODE_WHOLE = 6;   //全身照(手持身份证照)
	private int tempRequestCode = - 1;
	private ImageView mZimage, mFimage, mZFimage;
	private EditText mEname, mEno;
	private Button mTok;
	private MyApp myaap;
	private RelativeLayout mBar;
	private File tempFrontFile, tempReverseFile, tempWholeFile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_realname);

		intview ();
	}


	private void intview() {
		mBar = (RelativeLayout) findViewById (R.id.avrealname_progress_bar);
		myaap = (MyApp) getApplication ();

		mEname = (EditText) findViewById (R.id.avrealname_edit_name);
		mEno = (EditText) findViewById (R.id.avrealname_edit_no);
		mTok = (Button) findViewById (R.id.avrealname_text_ok);
		CommonUtils.setEditTextInhibitInputSpace (mEname);//禁止输入空字符
		CommonUtils.setEditTextInhibitInputSpace (mEno);//禁止输入空字符
		RxView.clicks (mTok)
				.throttleFirst (2, TimeUnit.SECONDS)
				.subscribe (new Consumer<Object> () {
					@Override
					public void accept(Object o) throws Exception {
						commit ();
					}
				});
//		mTok.setOnClickListener (this);
		findViewById (R.id.avrealname_image_back).setOnClickListener (this);
		mZimage = (ImageView) findViewById (R.id.avuserinfo_crad_z);
		mFimage = (ImageView) findViewById (R.id.avuserinfo_crad_f1);
		mZFimage = (ImageView) findViewById (R.id.avuserinfo_crad_zf);
		Datas_load datasLoad = myaap.getDatas_load ();
		if (datasLoad != null) {
//			String nopic = datasLoad.getUser_nopic ();
//			if (! TextUtils.isEmpty (nopic)) {
//				if (! nopic.startsWith ("http")) {
//					nopic = "http://" + nopic;
//				}
//				Glide.with (this).load (nopic).into (mZimage);
//
//			}
//			String nopic1 = datasLoad.getUser_nopic1 ();
//			if (! TextUtils.isEmpty (nopic1)) {
//				if (! nopic1.startsWith ("http")) {
//					nopic1 = "http://" + nopic1;
//				}
//				Glide.with (this).load (nopic1).into (mFimage);
//
//			}
//			String nopic2 = datasLoad.getUser_nopic2 ();
//			if (! TextUtils.isEmpty (nopic2)) {
//				if (! nopic2.startsWith ("http")) {
//					nopic2 = "http://" + nopic2;
//				}
//				Glide.with (this).load (nopic2).into (mZFimage);
//
//			}
			if (! myaap.getDatas_load ().getUser_no_status ().equals ("")) {
				mEname.setText (myaap.getDatas_load ().getUser_nicename ());
			}
			String userNo = datasLoad.getUser_no ();
			if (! TextUtils.isEmpty (userNo)) {
				mEno.setText (userNo);
			}
		}
		mZimage.setOnClickListener (this);
		mFimage.setOnClickListener (this);
		mZFimage.setOnClickListener (this);
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//			Log.e ("Permission", "init");
//			methodRequiresTwoPermission ();
//		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId ()) {
			case R.id.avrealname_image_back:
				finish ();
				break;

			case R.id.avuserinfo_crad_z:
				//身份证正面照
				tempRequestCode = REQUEST_CODE_FRONT;
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					methodRequiresTwoPermission ();
				} else {
					requestCode (tempRequestCode);
				}
				break;

			case R.id.avuserinfo_crad_f1:
				//身份证反面照
				tempRequestCode = REQUEST_CODE_REVERSE;
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					methodRequiresTwoPermission ();
				} else {
					requestCode (tempRequestCode);
				}
				break;

			case R.id.avuserinfo_crad_zf:
				//手持身份证
				tempRequestCode = REQUEST_CODE_WHOLE;
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					methodRequiresTwoPermission ();
				} else {
					requestCode (tempRequestCode);
				}
				break;

			case R.id.avrealname_text_ok:
				//提交上传
				commit ();
				break;

			default:
				break;
		}
	}

	private void commit() {
		String name = mEname.getText ().toString ();
		String idNumber = mEno.getText ().toString ();
		if (TextUtils.isEmpty (name)) {
			Toast.makeText (this, "姓名不能为空", Toast.LENGTH_SHORT).show ();
			return;
		}
		if (TextUtils.isEmpty (idNumber) || idNumber.length () < 10) {
			Toast.makeText (this, "请输入正确的银行卡号", Toast.LENGTH_SHORT).show ();
			return;
		}
		if (tempFrontFile == null) {
			Toast.makeText (this, "请上传身份证正面照", Toast.LENGTH_SHORT).show ();
			return;
		}
		if (tempReverseFile == null) {
			Toast.makeText (this, "请上传身份证反面面照", Toast.LENGTH_SHORT).show ();
			return;
		}
		if (tempWholeFile == null) {
			Toast.makeText (this, "请上传手持身份证照", Toast.LENGTH_SHORT).show ();
			return;
		}
		Log.e ("Commit", name + "/" + idNumber);
		Datas_load datasLoad = myaap.getDatas_load ();
		if (datasLoad != null) {
			List<File> listFile = new ArrayList<> ();
			listFile.add (tempFrontFile);
			listFile.add (tempReverseFile);
			listFile.add (tempWholeFile);
			mBar.setVisibility (View.VISIBLE);
			HttpMethods.getInstance ()
					.isAuth (mCommitObserver, datasLoad.getId (), name, idNumber, listFile);
		} else {
			Toast.makeText (this, "您还未登录", Toast.LENGTH_SHORT).show ();
		}
	}

	private Observer<BaseResponse> mCommitObserver = new Observer<BaseResponse> () {
		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(BaseResponse value) {
			mBar.setVisibility (View.GONE);
			if (value != null) {
				Log.e ("Realname", value.toString ());
				if (value.resultSuccess ()) {
					Toast.makeText (RealnameActivity.this, "上传成功，请耐心等待审核!", Toast.LENGTH_SHORT)
							.show ();
					if (myaap.getDatas_load () != null) {
						myaap.getDatas_load ().setUser_no_status ("2");
					}
					mTok.postDelayed (new Runnable () {
						@Override
						public void run() {
							setResult (122);
							finish ();
						}
					}, 1000);
				} else {
					Toast.makeText (RealnameActivity.this, value.getInfo (), Toast.LENGTH_SHORT)
							.show ();
				}
			}
		}

		@Override
		public void onError(Throwable e) {
			mBar.setVisibility (View.GONE);
			Log.e ("Realname", "onError" + e.getMessage ());
			Toast.makeText (RealnameActivity.this, e.getMessage (), Toast.LENGTH_SHORT)
					.show ();
		}

		@Override
		public void onComplete() {

		}
	};

	/**
	 * 单选并裁剪
	 *
	 * @param requestCode
	 */
	private void requestCode(int requestCode) {
		String cachePath = BoxingFileHelper.getCacheDir (this);
		if (TextUtils.isEmpty (cachePath)) {
			Toast.makeText (getApplicationContext (), R.string.boxing_storage_deny, Toast.LENGTH_SHORT)
					.show ();
			return;
		}
		Uri destUri = new Uri.Builder ()
				.scheme ("file")
				.appendPath (cachePath)
				.appendPath (String.format (Locale.US, "%s.jpg", System.currentTimeMillis ()))
				.build ();
		BoxingConfig singleCropImgConfig = new BoxingConfig (BoxingConfig.Mode.SINGLE_IMG).withCropOption (new BoxingCropOption (destUri));
		Boxing.of (singleCropImgConfig)
				.withIntent (this, BoxingActivity.class)
				.start (this, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult (requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case REQUEST_CODE_FRONT:
				case REQUEST_CODE_REVERSE:
				case REQUEST_CODE_WHOLE:
					final ArrayList<BaseMedia> medias = Boxing.getResult (data);
					BaseMedia baseMedia = medias.get (0);
					if (! (baseMedia instanceof ImageMedia)) {
						return;
					}
					final ImageMedia imageMedia = (ImageMedia) baseMedia;
					// the compress task may need time
					if (imageMedia.compress (new ImageCompressor (this), MAX_IMAGE_SIZE)) {
						imageMedia.removeExif ();
						handleImageFile (requestCode, imageMedia.getThumbnailPath ());
					}
					break;

			}
		}
	}

	private void handleImageFile(int requestCode, String imagePath) {
		if (TextUtils.isEmpty (imagePath)) return;
		String cachePath = BoxingFileHelper.getCacheDir (this);
		if (TextUtils.isEmpty (cachePath)) {
			Toast.makeText (getApplicationContext (), R.string.boxing_storage_deny, Toast.LENGTH_SHORT)
					.show ();
			return;
		}
		Log.e ("图片压缩", "----");
		File file = new File (cachePath, String.format (Locale.US, "%s.jpg", System.currentTimeMillis ()));
		try {
			boolean isSuccess = NativeUtil.mixCompress (imagePath, file.getAbsolutePath ());
			if (! isSuccess) {
				Toast.makeText (this, "您选择的图片太大", Toast.LENGTH_SHORT).show ();
				return;
			}
			switch (requestCode) {
				case REQUEST_CODE_FRONT:
					tempFrontFile = file;
					GlideApp.with (this).load (imagePath).placeholder(R.mipmap.icn__launch_oem)
							.error(R.mipmap.icn__launch_oem).into (mZimage);
					break;
				case REQUEST_CODE_REVERSE:
					tempReverseFile = file;
					GlideApp.with (this).load (imagePath).placeholder(R.mipmap.icn__launch_oem)
							.error(R.mipmap.icn__launch_oem).into (mFimage);
					break;
				case REQUEST_CODE_WHOLE:
					tempWholeFile = file;
					GlideApp.with (this).load (imagePath).placeholder(R.mipmap.icn__launch_oem)
							.error(R.mipmap.icn__launch_oem).into (mZFimage);
					break;

			}
		} catch (Exception e) {
		}
	}

	/**
	 * --------------------权限管理start---------------------------------
	 */

	private static final int REQUEST_READ_EXTERNAL_STORAGE = 8;

	//	@AfterPermissionGranted(REQUEST_READ_EXTERNAL_STORAGE)

	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
		if (EasyPermissions.hasPermissions (this, perms)) {
			Log.e ("Permission", "has permissions");
			if (tempRequestCode != - 1) {
				requestCode (tempRequestCode);
			}
		} else {
			Log.e ("Permission", "request permission");
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "应用需要读写权限",
					REQUEST_READ_EXTERNAL_STORAGE, perms);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		Log.e ("Permission", "onPermissionsGranted");
		if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
			if (tempRequestCode != - 1) {
				requestCode (tempRequestCode);
			}
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		Log.e ("Permission", "onPermissionsDenied");
		if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开读写权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", null)
					.create ()
					.show ();
		}
	}

	/**
	 * --------------------权限管理end-----------------------------------
	 */

	public static void samplingRateCompress(String filePath, File file) {
		// 数值越高，图片像素越低
		int inSampleSize = 8;
		BitmapFactory.Options options = new BitmapFactory.Options ();
		options.inJustDecodeBounds = false;
//	        options.inJustDecodeBounds = true;//为true的时候不会真正加载图片，而是得到图片的宽高信息。
		//采样率
		options.inSampleSize = inSampleSize;
		Bitmap bitmap = BitmapFactory.decodeFile (filePath, options);

		ByteArrayOutputStream baos = new ByteArrayOutputStream ();
		// 把压缩后的数据存放到baos中
		bitmap.compress (Bitmap.CompressFormat.JPEG, 100, baos);
		try {
			if (file.exists ()) {
				file.delete ();
			} else {
				file.createNewFile ();
			}
			FileOutputStream fos = new FileOutputStream (file);
			fos.write (baos.toByteArray ());
			fos.flush ();
			fos.close ();
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
}
